#include "sessionDemo.h"
#include "mainwindow.h"

#include <QMessageBox>

bool connectServer(int sock_fd)
{
    struct sockaddr_in serv_addr;
    /*******************设置服务器地址*********************/
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);
    serv_addr.sin_addr.s_addr = inet_addr("192.168.2.131");
    memset(&(serv_addr.sin_zero), 0, 8);

    /*********************连接至服务器*********************/
    if(connect(sock_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) != 0) //连接失败
    {
        close(sock_fd);     //关闭套接字
        return false;       //连接失败,返回false
    }
    return true;            //连接成功,返回true
}

bool checkUserInfo(int serv_fd, QString str_id, QString str_pwd, QString &username)
{
    int len;
    char buff[MAXSIZE];
    string sendMsg, recvMsg;
    //规范登录信息的格式
    sendMsg = "ID:" + str_id.toStdString() +"PWD:" + str_pwd.toStdString() + "#";
    send(serv_fd, sendMsg.c_str(), sendMsg.size(), 0);  //向服务器发送登录信息进行验证
    len = recv(serv_fd, buff, sizeof(buff), 0);          //接收服务器的验证结果
    buff[len] = '\0';
    recvMsg = buff;
    if(recvMsg == "OK.")    //如果服务器返回消息内容为"OK.",表示登录成功
    {
        len = recv(serv_fd, buff, sizeof(buff), 0);     //接收用户昵称
        buff[len] = '\0';
        username.sprintf("%s", buff);       //记录当前用户的昵称
        return true;        //登录成功,返回true
    }
    else
    {
        close(serv_fd);     //关闭套接字
        return false;       //登录失败,返回false
    }
}

void *recvMessage(void *lpParm)     //接收来自服务器的消息
{
    int len, serv_fd;
    struct def_msg msg;
    MainWindow *mainWdn = (MainWindow *)lpParm;     //得到聊天室类对象
    serv_fd = mainWdn->getServerFd();   //得到与服务器进行通信的套接字
    while(1)
    {
        len = recv(serv_fd, (char *)&msg, sizeof(msg), 0);  //接收消息
        if(len <= 0)    //检测到套接字关闭
        {
            break ;
        }
        mainWdn->classifyFunc(msg);     //分类处理消息
    }
    close(serv_fd);     //关闭套接字
    return NULL;
}
